﻿using Modbus.Messages;

namespace Modbus
{
	partial class ModbusClient
	{
		public void WriteMultipleCoils(byte slaveAddress, int startingAddress, bool[] outputs)
		{
			//
			// Input arguments validation.
			//

			Ensure.ArgumentInRange(SR.Argument_startingAddress, startingAddress, MinDataAddress, MaxDataAddress);
			Ensure.ArrayOfRequiredLength(SR.Argument_outputs, outputs, ModbusSpecification.MinQuantity,
				ModbusSpecification.WriteMultipleCoilsMaxQuantity);

			//
			// Internal state validation.
			//

			this.ThrowIfDisposed();

			//
			// Request creation.
			//

			WriteMultipleCoilsRequest request = new WriteMultipleCoilsRequest();

			request.FunctionCode = FunctionCodes.WriteMultipleCoils;
			request.StartingAddress = (ushort)(startingAddress);
			request.Quantity = (ushort)(outputs.Length);
			request.Data = DataUtility.EncodeDiscretes(outputs);

			//
			// Perform transaction.
			//
			
			if (slaveAddress == BroadcastAddress)
			{
				this.transport.Request(slaveAddress, request);
			}
			else
			{
				var response = this.transport.Request<StartingAddressQuantityMessage>(slaveAddress, request);

				//
				// Response validation.
				//

				if (response.StartingAddress != request.StartingAddress)
				{
					throw new MismatchResponseException(SR.ModbusMessageField_StartingAddress);
				}
				if (response.Quantity != request.Quantity)
				{
					throw new MismatchResponseException(SR.ModbusMessageField_Quantity);
				}
			}
		}
	}
}
